from datetime import datetime

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.views import ObtainJSONWebToken, jwt_response_payload_handler

from areas.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from goods.serializers import SKUSerializer
from users import serializers, constants
from users.models import User
from users.serializers import AddUserBrowsingHistorySerializer


class UsernameCountView(APIView):
    def get(self, request, username):
        """查询用户数量"""
        count = User.objects.filter(username=username).count()
        data = {
            "username": username,
            "count": count
        }
        return Response(data)


class MobileCountView(APIView):

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            "mobile": mobile,
            "count": count
        }
        return Response(data)


class UserView(CreateAPIView):
    serializer_class = serializers.CreateUserSerializer


class UserDetailView(RetrieveAPIView):
    """用户详情"""
    serializer_class = serializers.UserDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class EmailView(UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = serializers.EmailSerializer

    def get_object(self):
        """获取登录用户"""
        # self.request: 视图的request对象
        return self.request.user


class EmailVerifyView(APIView):

    def put(self, request):
        """
               用户邮箱验证:
               1. 获取token参数并进行校验(token必传，token是否有效)
               2. 设置用户邮箱验证的标记为True
               3. 返回应答，验证通过
               """
        # 1. 获取token参数并进行校验(token必传，token是否有效)
        token = request.query_params.get('token')
        if token is None:
            return Response({'message': '缺少token参数'}, status=status.HTTP_400_BAD_REQUEST)
        # 判断token 是否有效
        user = User.check_verify_email_token(token)

        if user is None:
            return Response({'message': 'token无效'}, status=status.HTTP_400_BAD_REQUEST)
        # 2. 设置用户邮箱验证的标记为True
        user.email_active = True
        user.save()

        # 3. 返回应答，验证通过
        return Response({'message': 'OK'})


class AddressViewSet(ModelViewSet):
    """
    用户地址的新增和修改
    """
    serializer_class = serializers.UserAddressSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        """用户地址列表数据"""
        queryset = self.get_queryset()

        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response(
            {
                'user_id': user.id,
                'default_address_id': user.default_address_id,
                'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
                'addresses': serializer.data,
            }
        )

    def create(self, request, *args, **kwargs):
        """保存用户地址数据"""

        # 检查用户地址数据数目是否超过上限
        count = request.user.addresses.filter(is_deleted=False).count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存的地址已经达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        """删除用户地址"""
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """设置默认地址"""
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({
            "message":'Ok',
        },status=status.HTTP_200_OK)

    @action(methods=['put'],detail=True)
    def title(self,request,pk=None):
        """修改标题"""
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address,data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


class UserBrowsingHistoryView(CreateAPIView):
    """
    用户浏览历史记录
    """
    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    # queryset = None
    #
    # def get_queryset(self):
    #     return self.queryset

    def get(self, request):
        """
        获取
        """
        user_id = request.user.id

        redis_conn = get_redis_connection("history")
        history = redis_conn.lrange("history_%s" % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)
        skus = []
        # 为了保持查询出的顺序与用户的浏览历史保存顺序一致
        for sku_id in history:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)

        s = SKUSerializer(skus, many=True)
        return Response(s.data)


# POST /authorizations/
class UserAuthorizeView(ObtainJSONWebToken):
    """登录视图"""
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            # 账号和密码正确
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            # 响应对象
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)

            # 补充操作: 调用合并购物车记录函数
            merge_cart_cookie_to_redis(request, user, response)
            return response

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
